package com.ecloud.common.web.config;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

/**
 * 日期格式化配置<br>
 * 处理LocalDateTime新时间类型<br>
 * 同时兼容JsonFormat注解
 *
 * @author LiuGangQiang Create in 2021/07/09
 */
@Configuration
public class AutoLocalDateTimeConfiguration {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    /**
     * 序列化配置
     *
     * @author LiuGangQiang Create in 2021/08/19
     * @return {@link LocalDateTimeSerializer}
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeSerializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 反序列化配置
     *
     * @author LiuGangQiang Create in 2021/08/19
     * @return {@link LocalDateTimeDeserializer}
     */
    @Bean
    public LocalDateTimeDeserializer localDateTimeDeserializer() {
        return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 序列化配置
     *
     * @author LiuGangQiang Create in 2021/08/19
     * @return {@link Jackson2ObjectMapperBuilderCustomizer}
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            /* 序列化设置 */
            builder.serializerByType(LocalDateTime.class, localDateTimeSerializer());
            /* 反序列化设置 */
            builder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer());
        };
    }
}
